package com.gitee.sidihuo.sse;

import com.alibaba.fastjson.JSONObject;
import com.gitee.sidihuo.sse.base.SseOkHttpEventSourceListener;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import okhttp3.sse.EventSource;
import okhttp3.sse.EventSourceListener;
import okhttp3.sse.EventSources;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.StopWatch;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

/**
 *  okhttp3流式Http请求
 */
@Slf4j
public class SseOkHttpClient {

    public static void post(SseOkHttpPara para, String requestJson, String url, Map<String, String> headers) {
        requestJson = StringUtils.isBlank(requestJson) ? new JSONObject().toJSONString() : requestJson;
        headers = headers == null ? new HashMap<>() : headers;
        log.info("sse ok http post begin {} url = {} jsonForm = {}", para.getId(), url, requestJson);
        RequestBody body = RequestBody.create(MediaType.parse("application/json"), requestJson);
        Request.Builder builder = new Request.Builder()
                .url(url)
                .headers(Headers.of(headers))
                .method("POST", body);
        log.info("SseOkHttpClient add post header {}", headers == null ? "null" : JSONObject.toJSONString(headers));

        Request request = builder.build();

        OkHttpClient client = new OkHttpClient();
        EventSource.Factory factory = EventSources.createFactory(client);

        CountDownLatch countDownLatch = new CountDownLatch(1);
        para.setCountDownLatch(countDownLatch);
        EventSourceListener listener = new SseOkHttpEventSourceListener(para);
        factory.newEventSource(request, listener);
        log.info("sse ok http begin post countDownLatch ... {}", para.getId());
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        boolean await = false;
        try {
            await = countDownLatch.await(5, TimeUnit.MINUTES);
        } catch (InterruptedException e) {
            log.warn("sse countDownLatch await InterruptedException", e);
        }
        stopWatch.stop();
        double totalTimeSeconds = stopWatch.getTotalTimeSeconds();
        if (await) {
            log.info("sse ok http end post countDownLatch finished {} totalTimeSeconds = {}", para.getId(), totalTimeSeconds);
        } else {
            log.warn("sse ok http end post countDownLatch failed {} totalTimeSeconds = {}", para.getId(), totalTimeSeconds);
        }

    }

}
